/*
 *   Licensed to the Apache Software Foundation (ASF) under one
 *   or more contributor license agreements.  See the NOTICE file
 *   distributed with this work for additional information
 *   regarding copyright ownership.  The ASF licenses this file
 *   to you under the Apache License, Version 2.0 (the
 *   "License"); you may not use this file except in compliance
 *   with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 *
 */

package org.apache.directory.mavibot.btree;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * This is a class which is used to create threads in the main BenchMarkGetValue.
 * It do get in the Btree during a moment. The tree and the time are passed in argument.
 * 
 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
 *
 */
public class MyThreadTest extends Thread{
	private long nbInsertCache=0;
	private long begin;
	private long duration;
	private long currenteDate;
	private ArrayList<TimeInsertion> tab=new ArrayList<TimeInsertion>();
	private int numThread;
	private CountDownLatch countDown;
	private PersistedBTree<Long, Long> btree;
	private int cacheSize;
	
	public ArrayList<TimeInsertion> getTab()
	{
		return tab;
	}
	
	public MyThreadTest( CountDownLatch c, int n, PersistedBTree<Long, Long> b, long d, int s )
	{
		numThread=n;
		countDown=c;
		btree=b;
		duration=d;
		cacheSize=s;
	}
	
	@Override
	public void run()
	{
		long value;
		long i=0;
		begin=System.currentTimeMillis();
		currenteDate=begin;
		while( currenteDate<begin+duration )
		{
			value=numThread * cacheSize + i;
			try {
				btree.insert( value, value );
				nbInsertCache++;
				if( currenteDate+1000<System.currentTimeMillis() )
				{
					tab.add( new TimeInsertion( System.currentTimeMillis()-begin, nbInsertCache ) );
					currenteDate=currenteDate+1000;
				}
			} catch ( IOException e ) {
				e.printStackTrace();
			}
			i++;
		}
		countDown.countDown();
	}
}
